package com.atguigu.srb.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.atguigu.srb.oss.service.FileService;
import com.atguigu.srb.oss.util.OssProperties;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Override
    public String upload(InputStream inputStream, String module, String filename) {


         // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(
                OssProperties.ENDPOINT,
                OssProperties.KEY_ID,
                OssProperties.KEY_SECRET);
        //判断oss实例是否存在：如果不存在则创建，如果存在则获取
        if (!ossClient.doesBucketExist(OssProperties.BUCKET_NAME)){
            //创建bucket
            ossClient.createBucket(OssProperties.BUCKET_NAME);
            //设置oss实例的访问权限：公共读
            ossClient.setBucketAcl(OssProperties.BUCKET_NAME, CannedAccessControlList.PublicRead);
        }
         //上传文件流
        //文件目录结构： "avatar/2021/09/10/uuid.jpg"
        //构建日期路径：avatar/2019/02/26/文件名
        String timeFolder = new DateTime().toString("/yyyy/MM/dd/");
        //文件名：uuid.扩展名
        filename = UUID.randomUUID().toString() + filename.substring(filename.lastIndexOf("."));
        System.out.println("filename22 = " + filename);
        //文件根路径
        String key = module + timeFolder + filename;
        System.out.println("key = " + key);
        //文件上传至阿里云
        ossClient.putObject(OssProperties.BUCKET_NAME, key, inputStream);

       // 关闭OSSClient。
        ossClient.shutdown();
        //阿里云文件绝对路径  https://srb-file-199.oss-cn-beijing.aliyuncs.com/avatar/02.jpg
        return "https://" + OssProperties.BUCKET_NAME + "." + OssProperties.ENDPOINT + "/" + key ;
    }

    @Override
    public void removeFile(String url) {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(
                OssProperties.ENDPOINT,
                OssProperties.KEY_ID,
                OssProperties.KEY_SECRET);
         //https://srb-file-199.oss-cn-beijing.aliyuncs.com/
        // test/2021/09/10/ef578203-83aa-43ec-b8c5-69f859f290e3.jpg
        //文件名（服务器上的文件路径）
        String host = "https://" + OssProperties.BUCKET_NAME + "." + OssProperties.ENDPOINT + "/";
        System.out.println("host = " + host.length());
        String objectName = url.substring(host.length());
        System.out.println("objectName = " + objectName);
        //删除文件
        ossClient.deleteObject(OssProperties.BUCKET_NAME,objectName);

        ossClient.shutdown();

    }
}
